
from main import db
from sqlalchemy.exc import InvalidRequestError
from main.utils import JSONHelper
from datetime import datetime
from sqlalchemy import or_, and_, func
from main.models import Result

def insert(object):
    try:
        object.time = datetime.now()
        db.session.add(object)
        db.session.commit()
        return True
    except InvalidRequestError:
        db.session.rollback()
    except Exception as e:
        print(e)
        return False


def update(object):
    try:
        object.time = datetime.now()
        db.session.commit()
        return True
    except InvalidRequestError:
        db.session.rollback()
    except Exception as e:
        print(e)
        return False


def delete(object):
    try:
        if type(object) == list:
            for o in object:
                db.session.delete(o)
                db.session.commit()
            else:
                db.session.delete(object)
                db.session.commit()
        return True
    except InvalidRequestError:
        db.session.rollback()
    except Exception as e:
        print(e)
        return False

def query():
    '''
    query all data
    :return: results
    '''
    return Result.query.all()


def query_by_user_id(user_id):
    '''
    query result by user_id
    :param user_id:
    :return: results
    '''
    return Result.query.filter(Result.user_id == user_id).all()


def count_by_user_id_and_game_id(user_id, game_id):
    return Result.query.filter(and_(Result.user_id == user_id, Result.game == game_id)).count()


if __name__ == '__main__':
    for i in query_by_user_id(1):
        print(i.to_json())
